package server.listener;

import com.alibaba.fastjson.JSON;
import common.body.TcpTunnelBody;
import common.enums.MsgTypeEnum;
import common.enums.ProtocolEnum;
import common.packet.BsPacket;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioListener;
import server.container.ProxyServer;


/**
 * @author gitama
 * @version 1.0
 * @date 2021/5/10 6:13 下午
 */
@Slf4j
public class HttpForwardServerListener implements ServerAioListener {

    @Override
    public boolean onHeartbeatTimeout(ChannelContext channelContext, Long interval, int heartbeatTimeoutCount) {
        log.debug("onHeartbeatTimeout");
        return false;
    }

    @Override
    public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {
        log.debug("onAfterConnected");
    }

    @Override
    public void onAfterDecoded(ChannelContext channelContext, Packet packet, int packetSize) throws Exception {
        String bsId = channelContext.getId();
        Tio.bindBsId(channelContext, bsId);
        String host = (String) channelContext.get("host");
        Integer port = (Integer) channelContext.get("port");

        BsPacket bsPacket = new BsPacket(MsgTypeEnum.TCP_TUNNEL_OPEN_REQ.getCode(),
                JSON.toJSONBytes(new TcpTunnelBody(bsId, ProtocolEnum.HTTP.getCode(), host, port)));

        String token = (String) channelContext.get("token");
        Tio.sendToBsId(ProxyServer.serverTioConfig, token, bsPacket);

    }

    @Override
    public void onAfterReceivedBytes(ChannelContext channelContext, int receivedBytes) throws Exception {
        log.debug(channelContext.userid);
    }

    @Override
    public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {
        log.debug(channelContext.userid);
    }

    @Override
    public void onAfterHandled(ChannelContext channelContext, Packet packet, long cost) throws Exception {
        log.debug(channelContext.userid);
    }

    @Override
    public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
        String bsId = channelContext.getId();

        BsPacket bsPacket = new BsPacket(MsgTypeEnum.TCP_TUNNEL_CLOSE_REQ.getCode(),
                JSON.toJSONBytes(new TcpTunnelBody(bsId, ProtocolEnum.HTTP.getCode())));

        String token = (String) channelContext.get("token");
        Tio.sendToBsId(ProxyServer.serverTioConfig, token, bsPacket);
    }

}
